﻿using com.gexin.rp.sdk.dto;
using com.igetui.api.openservice;
using com.igetui.api.openservice.igetui;
using com.igetui.api.openservice.igetui.template;
using com.igetui.api.openservice.payload;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace OtherLib.Getui
{
    public static class GetuiUtil
    {

        public static void SendMsgNotify(string Title, string Text, IDictionary<string, object> map, string CLIENTID)
        {
            var t = BuildNotificationTemplate(Title, Text, map);
            PushMessageToSingle(CLIENTID, t);
        }
        public static void SendMsgTransmission(IDictionary<string, object> map, string CLIENTID)
        {
            var t = TransmissionTemplateDemo(map);
            PushMessageToSingle(CLIENTID, t);
        }


        public static void SendMsgNotifyList(string Title, string Text, IDictionary<string, object> map, List<string> CLIENTIDs)
        {
            var t = BuildNotificationTemplate(Title, Text, map);
            PushMessageToList(CLIENTIDs, t);
        }
        public static void SendMsgTransmissionList(IDictionary<string, object> map, List<string> CLIENTIDs)
        {
            var t = TransmissionTemplateDemo(map);
            PushMessageToList(CLIENTIDs, t);
        }


        public static void SendMsgNotifyApp(string Title, string Text, IDictionary<string, object> map)
        {
            var t = BuildNotificationTemplate(Title, Text, map);
            pushMessageToApp(t);
        }
        public static void SendMsgTransmissionApp(IDictionary<string, object> map)
        {
            var t = TransmissionTemplateDemo(map);
            pushMessageToApp(t);
        }
        /// <summary>
        /// 单推
        /// </summary>
        private static void PushMessageToSingle(string CLIENTID, AbstractTemplate template)
        {

            IGtPush push = new IGtPush(GetuiConfig.Host, GetuiConfig.APPKEY, GetuiConfig.MASTERSECRET);

            //消息模版：TransmissionTemplate:透传模板

            // 单推消息模型
            SingleMessage message = new SingleMessage();
            message.IsOffline = true;                         // 用户当前不在线时，是否离线存储,可选
            message.OfflineExpireTime = 1000 * 3600 * 12;            // 离线有效时间，单位为毫秒，可选
            message.Data = template;
            //判断是否客户端是否wifi环境下推送，2为4G/3G/2G，1为在WIFI环境下，0为不限制环境
            //message.PushNetWorkType = 1;  


            com.igetui.api.openservice.igetui.Target target = new com.igetui.api.openservice.igetui.Target();
            target.appId = GetuiConfig.APPID;
            target.clientId = CLIENTID;
            //target.alias = ALIAS;
            try
            {
                String pushResult = push.pushMessageToSingle(message, target);

                System.Console.WriteLine("-----------------------------------------------");
                System.Console.WriteLine(pushResult);

                System.Console.WriteLine("-----------------------------------------------");
            }
            catch (Exception e)
            {
                //发送失败后的重发
                String pushResult = push.pushMessageToSingle(message, target);
                System.Console.WriteLine("-----------------------------------------------");
                System.Console.WriteLine(pushResult);
                System.Console.WriteLine("-----------------------------------------------");
            }
        }

        /// <summary>
        /// 推列表
        /// </summary>
        private static void PushMessageToList(List<string> CLIENTIDs, AbstractTemplate template)
        {
            // 推送主类（方式1，不可与方式2共存）
            IGtPush push = new IGtPush(GetuiConfig.Host, GetuiConfig.APPKEY, GetuiConfig.MASTERSECRET);
            // 推送主类（方式2，不可与方式1共存）此方式可通过获取服务端地址列表判断最快域名后进行消息推送，每10分钟检查一次最快域名
            //IGtPush push = new IGtPush("",APPKEY,MASTERSECRET);
            ListMessage message = new ListMessage();

            // 用户当前不在线时，是否离线存储,可选
            message.IsOffline = true;
            // 离线有效时间，单位为毫秒，可选
            message.OfflineExpireTime = 1000 * 3600 * 12;
            message.Data = template;
            //message.PushNetWorkType = 0;        //判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
            //设置接收者
            List<com.igetui.api.openservice.igetui.Target> targetList = new List<com.igetui.api.openservice.igetui.Target>();


            foreach (var item in CLIENTIDs)
            {
                com.igetui.api.openservice.igetui.Target target1 = new com.igetui.api.openservice.igetui.Target();
                target1.appId = GetuiConfig.APPID;
                target1.clientId = item;

                // 如需要，可以设置多个接收者
                //com.igetui.api.openservice.igetui.Target target2 = new com.igetui.api.openservice.igetui.Target();
                //target2.AppId = APPID;
                //target2.ClientId = "ddf730f6cabfa02ebabf06e0c7fc8da0";

                targetList.Add(target1);
                //targetList.Add(target2);
            }


            String contentId = push.getContentId(message);
            String pushResult = push.pushMessageToList(contentId, targetList);
            System.Console.WriteLine("-----------------------------------------------");
            System.Console.WriteLine(pushResult);
            System.Console.WriteLine("-----------------------------------------------");
        }
        /// <summary>
        /// 推整个App
        /// </summary>
        private static void pushMessageToApp(AbstractTemplate template)
        {
            // 推送主类（方式1，不可与方式2共存）
            IGtPush push = new IGtPush(GetuiConfig.Host, GetuiConfig.APPKEY, GetuiConfig.MASTERSECRET);
            // 推送主类（方式2，不可与方式1共存）此方式可通过获取服务端地址列表判断最快域名后进行消息推送，每10分钟检查一次最快域名
            //IGtPush push = new IGtPush("",APPKEY,MASTERSECRET);

            AppMessage message = new AppMessage();

            // 设置群推接口的推送速度，单位为条/秒，仅对pushMessageToApp（对指定应用群推接口）有效
            message.Speed = 100;


            // 用户当前不在线时，是否离线存储,可选
            message.IsOffline = false;
            // 离线有效时间，单位为毫秒，可选  
            message.OfflineExpireTime = 1000 * 3600 * 12;
            message.Data = template;
            //message.PushNetWorkType = 0;        //判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
            List<String> appIdList = new List<string>();
            appIdList.Add(GetuiConfig.APPID);

            //通知接收者的手机操作系统类型
            List<String> phoneTypeList = new List<string>();
            //phoneTypeList.Add("ANDROID");
            //phoneTypeList.Add("IOS");
            //通知接收者所在省份
            List<String> provinceList = new List<string>();
            //provinceList.Add("浙江");
            //provinceList.Add("上海");
            //provinceList.Add("北京");

            List<String> tagList = new List<string>();
            //tagList.Add("开心");

            message.AppIdList = appIdList;
            message.PhoneTypeList = phoneTypeList;
            message.ProvinceList = provinceList;
            message.TagList = tagList;


            String pushResult = push.pushMessageToApp(message);
            System.Console.WriteLine("-----------------------------------------------");
            System.Console.WriteLine(pushResult);
        }


        /// <summary>
        /// 透传模板动作内容
        /// </summary>
        /// <returns></returns>
        private static TransmissionTemplate TransmissionTemplateDemo(IDictionary<string, object> map)
        {
            var json = JsonConvert.SerializeObject(map);

            TransmissionTemplate template = new TransmissionTemplate();
            template.AppId = GetuiConfig.APPID;
            template.AppKey = GetuiConfig.APPKEY;
            //应用启动类型，1：强制应用启动 2：等待应用启动
            template.TransmissionType = 1;
            //透传内容  
            template.TransmissionContent = json;

            com.igetui.api.openservice.igetui.template.notify.Notify notify = new com.igetui.api.openservice.igetui.template.notify.Notify();
            notify.Title = "titleee";
            notify.Content = "contentee";
            notify.Intent = "intent:#Intent;mm;end";
            //notify.Payload='payloadtest';
            notify.Type = NotifyInfo.Types.Type._payload;
            template.set3rdNotifyInfo(notify);

            APNPayload apnpayload = new APNPayload();
            apnpayload.Badge = +1;
            //apnpayload.Sound = "com.gexin.ios.silence";
            apnpayload.addCustomMsg("payload", json);
            apnpayload.ContentAvailable = 1;
            //apnpayload.Category = "ACTIONABLE";
            //apnpayload.VoicePlayType = 2;
            //apnpayload.VoicePlayMessage = "支付宝到账一千万元整";
            apnpayload.AlertMsg = new SimpleAlertMsg(json);

            template.setAPNInfo(apnpayload);
            var date = DateTime.Now;
            String begin = date.ToString("yyyy-MM-dd HH:mm:ss");
            String end = date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            template.setDuration(begin, end);


            return template;
        }

        /// <summary>
        /// 通知透传模板动作内容
        /// </summary>
        /// <returns></returns>
        private static NotificationTemplate BuildNotificationTemplate(string Title, string Text, IDictionary<string, object> map)
        {
            var json = JsonConvert.SerializeObject(map);

            NotificationTemplate template = new NotificationTemplate();
            template.AppId = GetuiConfig.APPID;
            template.AppKey = GetuiConfig.APPKEY;
            //通知栏标题
            template.Title = Title;
            //通知栏内容     
            template.Text = Text;
            //通知栏显示本地图片
            template.Logo = "";
            //通知栏显示网络图标
            template.LogoURL = "";
            //应用启动类型，1：强制应用启动  2：等待应用启动
            template.TransmissionType = 1;
            //透传内容  
            template.TransmissionContent = json;
            //接收到消息是否响铃，true：响铃 false：不响铃   
            template.IsRing = true;
            //接收到消息是否震动，true：震动 false：不震动   
            template.IsVibrate = true;
            //接收到消息是否可清除，true：可清除 false：不可清除    
            template.IsClearable = true;
            //设置通知定时展示时间，结束时间与开始时间相差需大于6分钟，消息推送后，客户端将在指定时间差内展示消息（误差6分钟）
            //String begin = "2015-03-06 14:36:10";
            //String end = "2015-03-06 14:46:20";
            var date = DateTime.Now;
            String begin = date.ToString("yyyy-MM-dd HH:mm:ss");
            String end = date.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            template.setDuration(begin, end);

            DictionaryAlertMsg alertMsg = new DictionaryAlertMsg();
            alertMsg.Body = json;
            alertMsg.LaunchImage = "";
            // iOS8.2以上版本支持
            alertMsg.Title = Title;
            alertMsg.TitleLocKey = Title;
            //alertMsg.TitleLocArgs.Add(Text);

            APNPayload apnpayload = new APNPayload();
            apnpayload.Badge = +1;
            //apnpayload.Sound = "com.gexin.ios.silence";
            apnpayload.addCustomMsg("payload", json);
            apnpayload.ContentAvailable = 1;
            //apnpayload.Category = "ACTIONABLE";
            //apnpayload.VoicePlayType = 2;
            //apnpayload.VoicePlayMessage = "支付宝到账一千万元整";
            apnpayload.AlertMsg = alertMsg;

            template.setAPNInfo(apnpayload);

            return template;
        }

    }
}
